package com.huan.drools.querys;

import lombok.extern.slf4j.Slf4j;
import org.drools.core.event.DebugProcessEventListener;
import org.kie.api.KieServices;
import org.kie.api.event.rule.DebugAgendaEventListener;
import org.kie.api.event.rule.DebugRuleRuntimeEventListener;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.*;

/**
 * drools 实时查询，当工作内存中的数据发生变化后，立马知道
 *
 * @author huan.fu
 * @date 2022/5/15 - 18:55
 */
@Slf4j
public class DroolsLiveQueryApplication {

    public static void main(String[] args) {
        KieServices kieServices = KieServices.get();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("query-ksession");
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());
        kieSession.addEventListener(new DebugAgendaEventListener());
        kieSession.addEventListener(new DebugProcessEventListener());

        // 实时查询
        kieSession.openLiveQuery("query02", new Object[]{20}, new ViewChangedEventListener() {
            @Override
            public void rowInserted(Row row) {
                Person person = (Person) row.get("$p");
                log.info("实时查询-query02向工作内存中插入Person: {}", person);
            }

            @Override
            public void rowDeleted(Row row) {
                Person person = (Person) row.get("$p");
                log.info("实时查询-query02向工作内存中删除Person: {}", person);
            }

            @Override
            public void rowUpdated(Row row) {
                Person person = (Person) row.get("$p");
                log.info("实时查询-query02向工作内存中更新Person: {}", person);
            }
        });

        Person person1 = new Person("张三", 16);
        kieSession.insert(person1);

        kieSession.fireAllRules();

        kieSession.dispose();
    }
}
